﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;

namespace MDX_Studio_v2
{
	public partial class ParametersWindow : DockContent
	{
		private Context _Context;
		public Context Context
		{
			set
			{
				_Context = value;
				UpdateDisplay();
			}
		}

		private string _queryText = "";
		private Dictionary<string, string> _parameters;
		public string QueryText
		{
			set
			{
				_queryText = value;
				UpdateDisplay();
				Console.WriteLine("Query updated");
			}
		}

		public string ParsedQuery
		{
			get
			{
				return ParseQuery();
			}
		}

		public ParametersWindow()
		{
			InitializeComponent();
		}

		private void PopulateWindow()
		{
			_parameters = new Dictionary<string, string>();

			string sPattern = "@[a-zA-Z1-9]+";

			int i = 0;
			this.Controls.Clear();
			foreach (System.Text.RegularExpressions.Match param in System.Text.RegularExpressions.Regex.Matches(_queryText, sPattern))
			{
				string tmp = "";
				if (_parameters.TryGetValue(param.Value, out tmp) == false)
				{
					// Generate label
					Label l = new Label();
					l.Anchor = ((AnchorStyles)(((AnchorStyles.Top | AnchorStyles.Left) | AnchorStyles.Right)));
					l.AutoSize = true;
					l.Name = "label" + i;
					l.Text = param.Value;
					l.Location = new Point(12, 18 + 26 * i);
					this.Controls.Add(l);

					// Generate Textbox
					TextBox t = new TextBox();
					t.Anchor = ((AnchorStyles)(((AnchorStyles.Top | AnchorStyles.Left) | AnchorStyles.Right)));
					t.Name = param.Value;

					string defaultVal = ParseParameterDefaultValues(param.Value);
					t.Text = defaultVal;

					t.Size = new System.Drawing.Size(165, 20);
					t.Location = new Point(100, 15 + 26 * i);
					this.Controls.Add(t);

					_parameters.Add(param.Value, defaultVal);

					i++;
				}
			}
		}

		private void UpdateDisplay()
		{
			PopulateWindow();
		}

		private string ParseParameterDefaultValues(string paramName)
		{
			string sPattern = "(" + paramName + "=)([a-zA-z0-9]+)";

			foreach (System.Text.RegularExpressions.Match param in System.Text.RegularExpressions.Regex.Matches(_queryText, sPattern))
			{
				return param.Groups[2].Value;
			}

			return "";
		}

		private string ParseQuery()
		{
			string parsed = _queryText;

			foreach (Control c in this.Controls)
			{
				if (c is TextBox)
				{
					parsed = parsed.Replace(((TextBox)c).Name, "\"" + ((TextBox)c).Text + "\"");
				}
			}

			return parsed;
		}
	}
}
